﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using AEM.Utils;
using Actions = AEM.Data.BLL.Actions;

namespace AEM
{
    /// <summary>
    /// UserManage.xaml 的交互逻辑
    /// </summary>
    public partial class UserManage : Window
    {
        public UserManage()
        {
            this.InitializeComponent();
            this.Loaded += new RoutedEventHandler(UserManage_Loaded);
            this.TitleBar.MouseLeftButtonDown += new MouseButtonEventHandler(UserManage_MouseLeftButtonDown);
            this.userList.SelectionChanged += new SelectionChangedEventHandler(userList_SelectionChanged);
            this.userAdd.Click += new RoutedEventHandler(userAdd_Click);
            this.userEdit.Click += new RoutedEventHandler(userEdit_Click);
            this.userDelete.Click += new RoutedEventHandler(userDelete_Click);

            //this.userGroup.SelectionChanged += new SelectionChangedEventHandler(userGroup_SelectionChanged);
        }

        void userList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (null == (sender as ListView).SelectedItem) return;
            AEM.Data.Model.User row = (sender as ListView).SelectedItem as AEM.Data.Model.User;

            if (null != row)
            {
                this.userName.Text = row.UserName;
                this.userPassword.Password = "****************";
                //this.userGroup.SelectedItem = (UserGroup)row.UserGroup;
                GetPermission((int)row.UserPermission);
            }
        }

        void UserManage_Loaded(object sender, RoutedEventArgs e)
        {
            this.userList.ItemsSource = Data.DAL.User.List("UserPermission<>-1");
            //this.userGroup.ItemsSource = StringHelper.EnumToList<UserGroup>();
            //this.userGroup.SelectedIndex = 0;

            this.connection_status.Tag = Data.Enum.ControlPoints.ConnectionStatus;
            this.operating_status.Tag = Data.Enum.ControlPoints.OperatingStatus;
            this.applications_logs.Tag = Data.Enum.ControlPoints.ApplicationLogs;
            this.data_statistics.Tag = Data.Enum.ControlPoints.DataStatistics;
            this.resetpassword.Tag = Data.Enum.ControlPoints.ResetPassword;
            this.exportprint.Tag = Data.Enum.ControlPoints.ExportPrint;

            this.lift_locked.Tag = Data.Enum.ControlPoints.LockLift;
            this.liftControl1.Tag = Data.Enum.ControlPoints.UDF1;
            this.liftControl2.Tag = Data.Enum.ControlPoints.UDF2;
            this.liftControl3.Tag = Data.Enum.ControlPoints.UDF3;
            this.liftRemotecall.Tag = Data.Enum.ControlPoints.RemoteCall;
            this.liftVipcall.Tag = Data.Enum.ControlPoints.VIPCall;
            this.lifthallcall.Tag = Data.Enum.ControlPoints.HallCall;

            this.escalator_up.Tag = Data.Enum.ControlPoints.RisingStart;
            this.escalator_down.Tag = Data.Enum.ControlPoints.DescendingStart;
            this.escalator_locked.Tag = Data.Enum.ControlPoints.StopRuning;

            this.trails_forword.Tag = Data.Enum.ControlPoints.ForwardStart;
            this.trails_backword.Tag = Data.Enum.ControlPoints.BackwardStart;
            this.trails_locked.Tag = Data.Enum.ControlPoints.TrailsStopRuning;

            this.userPassword.FocusableChanged += new DependencyPropertyChangedEventHandler((ss, ee) =>
            {
                if (this.userPassword.Password.Trim() == "****************")
                    this.userPassword.Password = "";
            });
        }

        void userGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ResetCheckBox();
        }

        private void ResetCheckBox()
        {
            foreach (CheckBox c in this.LayoutRoot.Children.OfType<CheckBox>())
            {
                c.IsChecked = false;
            }
        }

        void userAdd_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (string.IsNullOrEmpty(this.userName.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("UserName") as string); return; }
            if (string.IsNullOrEmpty(this.userPassword.Password.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("UserPassword") as string); return; }

            if (!this.userName.Text.checkUserName()) { errmsg.Text = this.TryFindResource("FormatUserName") as string; return; }
            if (!this.userPassword.Password.checkPwd()) { errmsg.Text = this.TryFindResource("FormatPassword") as string; return; }


            AEM.Data.Model.User row = new Data.Model.User();
            row.UserName = this.userName.Text.Trim();
            row.UserGroup = 1; //Convert.ToInt32((Data.Enum.UserGroup)this.userGroup.SelectedItem);
            row.UserPermission = GetPermission();
            row.UserPWD = string.IsNullOrEmpty(this.userPassword.Password.Trim()) ? "123456".toMD5() : this.userPassword.Password.Trim().toMD5();
            row.CreateDate = DateTime.Now;
            row.LastLoginDate = DateTime.Now;
            row.LastUpdatePwdDate = DateTime.Now;

            Actions.User.AdduserResult ret = Actions.User.Adduser(row);
            switch (ret)
            {
                case Actions.User.AdduserResult.UserIsNull:
                    break;
                case Actions.User.AdduserResult.UserAlreadyExist:
                    errmsg.Text = string.Format(this.TryFindResource("AlreadyExists") as string, this.TryFindResource("UserName") as string);
                    break;
                case Actions.User.AdduserResult.OK:
                    errmsg.Text = this.TryFindResource("successfuladd") as string;
                    this.userName.Clear();
                    this.userPassword.Clear();
                    this.userList.ItemsSource = Data.DAL.User.List("UserPermission<>-1");
                    this.userList.Items.Refresh();
                    ResetCheckBox();
                    break;
            }
        }

        void userEdit_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (null == this.userList.SelectedItem) { errmsg.Text = this.TryFindResource("SelectOne") as string; return; }
            if (string.IsNullOrEmpty(this.userName.Text.Trim())) { errmsg.Text = string.Format(this.TryFindResource("NotBeNullOrEmpty") as string, this.TryFindResource("UserName") as string); return; }
            if (!this.userName.Text.checkUserName()) { errmsg.Text = this.TryFindResource("FormatUserName") as string; return; }
            if (!string.IsNullOrEmpty(this.userPassword.Password.Trim()) && this.userPassword.Password.Trim() != "****************")
                if (!this.userPassword.Password.checkPwd()) { errmsg.Text = this.TryFindResource("FormatPassword") as string; return; }

            AEM.Data.Model.User row = this.userList.SelectedItem as AEM.Data.Model.User;
            row.UserName = this.userName.Text.Trim();
            row.UserGroup = 1; //(int)(Data.Enum.UserGroup)this.userGroup.SelectedItem;
            row.UserPermission = GetPermission();
            row.UserPWD = (string.IsNullOrEmpty(this.userPassword.Password.Trim()) || this.userPassword.Password.Trim() == "****************") ? row.UserPWD : this.userPassword.Password.Trim().toMD5();

            Actions.User.ModifiyUserResult ret = Actions.User.Modifiyuser(row);
            switch (ret)
            {
                case Actions.User.ModifiyUserResult.UserIsNotExist:
                    errmsg.Text = string.Format(this.TryFindResource("IsNotExist") as string, this.TryFindResource("UserName") as string);
                    break;
                case Actions.User.ModifiyUserResult.OK:
                    errmsg.Text = this.TryFindResource("successfulupdate") as string;
                    this.userName.Clear();
                    this.userPassword.Clear();
                    this.userList.ItemsSource = Data.DAL.User.List("UserPermission<>-1");
                    this.userList.Items.Refresh();
                    ResetCheckBox();
                    break;
            }
        }

        void userDelete_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (null == this.userList.SelectedItem) { errmsg.Text = this.TryFindResource("SelectOne") as string; return; }
            AEM.Data.Model.User row = this.userList.SelectedItem as AEM.Data.Model.User;
            if (MessageBoxResult.Yes == MessageBox.Show(string.Format(this.TryFindResource("AskForDelete") as string, row.UserName), this.TryFindResource("MessageBoxTitle") as string, MessageBoxButton.YesNo, MessageBoxImage.Warning))
            {
                Actions.User.DeleteuserResult ret = Actions.User.Deleteuser((int)row.ID);
                switch (ret)
                {
                    case Actions.User.DeleteuserResult.UserIsNotExist:
                        errmsg.Text = string.Format(this.TryFindResource("IsNotExist") as string, this.TryFindResource("UserName") as string);
                        break;
                    case Actions.User.DeleteuserResult.OK:
                        errmsg.Text = this.TryFindResource("successfuldelete") as string;
                        this.userName.Clear();
                        this.userPassword.Clear();
                        this.userList.ItemsSource = Data.DAL.User.List("UserPermission<>-1");
                        this.userList.Items.Refresh();
                        ResetCheckBox();
                        break;
                }
            }
        }

        /// <summary>
        /// 从界面上获取勾选的Permission
        /// </summary>
        /// <returns></returns>
        int GetPermission()
        {
            int ret = 0;
            foreach (CheckBox c in this.LayoutRoot.Children.OfType<CheckBox>())
            {
                if (c.IsChecked.Value) ret |= (int)(Data.Enum.ControlPoints)c.Tag;
            }
            return ret;
        }

        /// <summary>
        /// 跟据 Permission 设置界面上CheckBox是否勾选
        /// </summary>
        /// <param name="value"></param>
        void GetPermission(int value)
        {
            foreach (CheckBox c in this.LayoutRoot.Children.OfType<CheckBox>())
            {
                if ((value & (int)(Data.Enum.ControlPoints)c.Tag) > 0) c.IsChecked = true;
                else c.IsChecked = false;
            }
        }

        void UserManage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void sys_button_close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void sys_button_min_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
    }
}